import { createRouter, createWebHistory } from 'vue-router'
import HomeView from '../views/HomeView.vue'
import LoginView from '../views/LoginView.vue'
import StudentManage from '../views/StudentManage.vue'
import RoomManage from '../views/RoomManage.vue'
import MachineManage from '../views/MachineManage.vue'
import SessionManage from '../views/SessionManage.vue'
import store from '../store'
import * as process from "echarts";
import RegisterView from '../views/RegisterView.vue'

const routes = [
  {
    path: '/',
    name: 'home',
    component: HomeView,
    meta: { requiresAuth: true }
  },
  {
    path: '/login',
    name: 'login',
    component: LoginView,
    meta: { requiresGuest: true }
  },
  {
    path: '/students',
    name: 'students',
    component: StudentManage,
    meta: { requiresAuth: true }
  },
  {
    path: '/rooms',
    name: 'rooms',
    component: RoomManage,
    meta: { requiresAuth: true }
  },
  {
    path: '/machines',
    name: 'machines',
    component: MachineManage,
    meta: { requiresAuth: true }
  },
  {
    path: '/sessions',
    name: 'sessions',
    component: SessionManage,
    meta: { requiresAuth: true }
  },
  {
    path: '/:pathMatch(.*)*',
    redirect: '/'
  },
  {
    path: '/register',
    name: 'register',
    component: RegisterView,
    meta: { requiresGuest: true }
  },
]

const router = createRouter({
  history: createWebHistory(process.env.BASE_URL),
  routes
})

// 路由守卫
router.beforeEach((to, from, next) => {
  const token = store.state.token
  const isAuthenticated = !!token
  
  if (to.meta.requiresAuth && !isAuthenticated) {
    next('/login')
  } else if (to.meta.requiresGuest && isAuthenticated) {
    next('/')
  } else {
    next()
  }
})

export default router